#include "tcp_server.h"
#include <vector>
#include <functional>
#include <algorithm>
#include <thread>
#include <boost/bind.hpp>
#include "logger.h"

const static int kIndexMask = 0x7FFFFFFF;

TcpServer::TcpServer(const std::string& port, const std::string addr)
:io_pool_(),
acceptor_(io_pool_.getIOService()),
signal_set_(io_pool_.getIOService()),
current_index_(0)
{
	//signal_set_.add(SIGINT);
	signal_set_.add(SIGTERM);
	signal_set_.async_wait(std::bind(&TcpServer::HandlStop, this));

	tcp::resolver resolver(acceptor_.get_io_service());
	tcp::resolver::query query(addr, port);
	tcp::endpoint endpoint = *resolver.resolve(query);
	acceptor_.open(endpoint.protocol());
	acceptor_.set_option(tcp::acceptor::reuse_address(true));
	acceptor_.bind(endpoint);
	acceptor_.listen();
}

void TcpServer::Start()
{
	StartAccept();
	io_pool_.run();
}

void TcpServer::StartAccept()
{
	new_connection_.reset(new TcpConnection(io_pool_.getIOService()));

	int index = ++current_index_ & kIndexMask;
	new_connection_->id(index);

	acceptor_.async_accept(new_connection_->socket(),
		boost::bind(&TcpServer::OnConnection, this, boost::asio::placeholders::error));
}

void TcpServer::OnConnection(const boost::system::error_code& err)
{
	if (!err)
	{
		new_connection_->Start();
		LOG4CPLUS_DEBUG(Log, "new connection from " << new_connection_->remote_addr());
	}
	else
	{
		LOG4CPLUS_ERROR(Log, "accept error: " << err.message());
	}
	
	StartAccept();
}